package com.minidb.cli;

import com.minidb.engine.*;
import com.minidb.sql_compiler.*;
import com.minidb.storage.*;
import com.minidb.utils.Constants;

public class TestRunner {

    // 测试用例
    private static final String[] NORMAL_TESTS = {
        "CREATE TABLE users(id INT, name TEXT, age INT)",
        "INSERT INTO users(id, name, age) VALUES(1, 'Alice', 25)",
        "INSERT INTO users(id, name, age) VALUES(2, 'Bob', 30)",
        "SELECT * FROM users",
        "SELECT name, age FROM users WHERE age > 20",
        "DELETE FROM users WHERE id = 1",
        "SELECT * FROM users"
    };
    
    private static final String[] ERROR_TESTS = {
        "CREATE TABLE users(id INT, name TEXT, age INT)", // 重复建表
        "INSERT INTO nonexistent(id) VALUES(1)", // 表不存在
        "INSERT INTO users(id, name) VALUES(1, 'Alice', 25)", // 列数不匹配
        "INSERT INTO users(id, name, age) VALUES('invalid', 'Alice', 25)", // 类型错误
        "SELECT nonexistent FROM users", // 列不存在
        "SELECT * FROM users WHERE nonexistent = 1" // WHERE中列不存在
    };
    
    public static void main(String[] args) {
        System.out.println("=== MiniDB 系统化测试 ===");
        
        // 初始化组件 - 修复构造函数调用
        FileManager fileManager = new FileManager("test_data");
        BufferPool bufferPool = new BufferPool(
            Constants.BUFFER_POOL_CAPACITY,
            fileManager,
            Constants.ReplacementPolicy.LRU
        );
        
        SystemCatalog systemCatalog = new SystemCatalog(fileManager, bufferPool);
        CatalogManager catalogManager = new CatalogManager(fileManager, systemCatalog);
        catalogManager.loadFromSystemTable();
        
        StorageEngine storageEngine = new StorageEngine(bufferPool, fileManager, catalogManager);
        
        Catalog catalog = new Catalog(catalogManager);
        SyntaxParser parser = new SyntaxParser();
        SemanticAnalyzer semantic = new SemanticAnalyzer(catalog);
        Executor executor = new Executor(storageEngine, catalogManager);
        
        int passCount = 0;
        int totalCount = 0;
        
        // 正常功能测试
        System.out.println("\n--- 正常功能测试 ---");
        for (String sql : NORMAL_TESTS) {
            totalCount++;
            try {
                SQLStatement stmt = parser.parse(sql);
                semantic.analyze(stmt);
                
                ExecutionPlan plan = new ExecutionPlan();
                plan.type = stmt.type;
                plan.tableName = stmt.tableName;
                plan.columns = stmt.columns;
                plan.columnTypes = stmt.columnTypes;
                plan.values = stmt.values;
                plan.condition = stmt.condition;
                
                String result = executor.executePlan(plan);
                System.out.println("✅ PASS: " + sql);
                System.out.println("   结果: " + result.split("\n")[0]);
                passCount++;
            } catch (Exception e) {
                System.out.println("❌ FAIL: " + sql);
                System.out.println("   错误: " + e.getMessage());
            }
        }
        
        // 错误用例测试
        System.out.println("\n--- 错误用例测试 ---");
        for (String sql : ERROR_TESTS) {
            totalCount++;
            try {
                SQLStatement stmt = parser.parse(sql);
                semantic.analyze(stmt);
                
                ExecutionPlan plan = new ExecutionPlan();
                plan.type = stmt.type;
                plan.tableName = stmt.tableName;
                plan.columns = stmt.columns;
                plan.columnTypes = stmt.columnTypes;
                plan.values = stmt.values;
                plan.condition = stmt.condition;
                
                executor.executePlan(plan);
                System.out.println("❌ FAIL: " + sql + " (应该报错但没有)");
            } catch (Exception e) {
                System.out.println("✅ PASS: " + sql);
                System.out.println("   正确检测到错误: " + e.getMessage());
                passCount++;
            }
        }
        
        // 持久化测试
        System.out.println("\n--- 持久化测试 ---");
        totalCount++;
        try {
            // 重新初始化（模拟重启）- 修复构造函数调用
            fileManager = new FileManager("test_data");
            bufferPool = new BufferPool(
                Constants.BUFFER_POOL_CAPACITY,
                fileManager,
                Constants.ReplacementPolicy.LRU
            );
            
            systemCatalog = new SystemCatalog(fileManager, bufferPool);
            catalogManager = new CatalogManager(fileManager, systemCatalog);
            catalogManager.loadFromSystemTable();
            
            storageEngine = new StorageEngine(bufferPool, fileManager, catalogManager);
            executor = new Executor(storageEngine, catalogManager);
            
            catalog = new Catalog(catalogManager);
            semantic = new SemanticAnalyzer(catalog);
            
            SQLStatement stmt = parser.parse("SELECT * FROM users");
            semantic.analyze(stmt);
            
            ExecutionPlan plan = new ExecutionPlan();
            plan.type = stmt.type;
            plan.tableName = stmt.tableName;
            plan.columns = stmt.columns;
            plan.values = stmt.values;
            plan.condition = stmt.condition;
            
            String result = executor.executePlan(plan);
            System.out.println("✅ PASS: 持久化测试");
            System.out.println("   重启后数据仍存在");
            passCount++;
        } catch (Exception e) {
            System.out.println("❌ FAIL: 持久化测试");
            System.out.println("   错误: " + e.getMessage());
        }
        
        // 测试总结
        System.out.println("\n=== 测试总结 ===");
        System.out.println(String.format("通过: %d/%d (%.1f%%)", 
            passCount, totalCount, (double)passCount/totalCount*100));
        
        if (passCount == totalCount) {
            System.out.println("🎉 所有测试通过！");
        } else {
            System.out.println("⚠️  部分测试失败，需要修复");
        }
    }
}